<template>
  <view class="login">
    <view>寻伴社交平台</view>
    <input type="text" class="input-box" v-model="phone" placeholder="请输入手机号" />
    <view class="login-wrap">
      <input type="password" class="input-box verification-code" v-model="code" placeholder="请输入验证码" />
      <view class="get-verification-code">
        <u-verification-code
          :seconds="seconds"
          @end="end"
          @start="start"
          ref="uCode"
          @change="codeChange"
        ></u-verification-code>
        <u-button @click.stop="getCode">{{ tips }}</u-button>
      </view>
    </view>
    <u-toast ref="uToast"></u-toast>
    <button class="login-btn" @click="loginForPhone">登录</button>
  </view>
</template>

<script lang="ts">
  import { defineComponent, ref } from '@vue/composition-api';
  import { useUview, useDomRefs } from '@/hooks/uview.hooks';
  import * as login from '@/api/login';
  import { Message } from '@/libs/index';
  import * as uniPromise from '@/utils/uniPromise';
  import { TokenModule } from '@/store/modules/token.module';
  import { UserModule } from '@/store/modules/user.module';
  import { useRouter } from '@/constants/router';
  import { useStore } from '@/store';
  import { useConnectGoEasy } from '@/hooks/go-easy.hooks';
  import { STORAGE_KEY, useStorage } from '@/hooks/storage.hoos';
  import { CurrentUser } from '@/types/storage/current-user.storage.type';

  export default defineComponent({
    setup() {
      const userModule = useStore(UserModule);
      const tokenModule = useStore(TokenModule);
      const $u = useUview();
      const domRefs = useDomRefs();
      const phone = ref('');
      const code = ref('');
      const seconds = 30;
      const tips = ref('');
      const showError = ref<boolean>(false);
      let token = '';
      const router = useRouter();

      function end() {
        $u.toast('倒计时结束');
      }

      function start() {
        $u.toast('倒计时开始');
      }

      function codeChange(text: string) {
        console.log(text);
        tips.value = text;
      }

      async function getCode() {
        type UCodeComponent = {
          canGetCode: boolean;
          start: () => void;
        };
        const uCodeComponent = domRefs<UCodeComponent>({}, 'uCode');
        if (uCodeComponent.canGetCode) {
          // 模拟向后端请求验证码
          uni.showLoading({
            title: '正在获取验证码'
          });
          try {
            const res = await login.getCode(phone.value);
            console.log(res);
            token = res.data;

            uni.hideLoading();
            // 这里此提示会被this.start()方法中的提示覆盖
            uni.$u.toast('验证码已发送');
            // 通知验证码组件内部开始倒计时
            uCodeComponent.start();
          } catch (error) {
            uni.hideLoading();
            uni.$oto.log.info(error);
            Message.error(error);
            console.error(error);
          }
        } else {
          uni.$u.toast('倒计时结束后再发送');
        }
      }

      async function loginForPhone() {
        if (!phone.value) {
          Message.warning('请先填写手机号');
          return;
        }
        if (!tips.value) {
          Message.warning('请先填写验证码');
          return;
        }
        try {
          const { userInfo } = await uniPromise.getUserProfile({
            desc: '用于完善会员资料'
          });

          const res = await login.login({
            ...userInfo,
            language: 'zh_CN',
            phone: phone.value,
            token,
            code: code.value
          });
          console.log(res);
          tokenModule.setToken(res.data.token);
          userModule.setUserInfo(res.data.userInfo);
          userModule.setLoginStatus(true);
          const [currentUser, setCurrentUser] = useStorage<CurrentUser>(STORAGE_KEY.CURRENT_USER);
          setCurrentUser({
            uuid: String(res.data.userInfo.id),
            name: res.data.userInfo.nickName,
            avatar: res.data.userInfo.avatarUrl
          });
          console.log(currentUser);
          console.log(userModule.userInfo);
          await useConnectGoEasy({
            id: res.data.userInfo.id,
            data: {
              name: res.data.userInfo.nickName,
              avatar: res.data.userInfo.avatarUrl
            }
          });
          await Message.success('登陆成功！');
          router.navigateBack({
            delta: 1
          });
        } catch (error) {
          console.log(error);
          Message.error('登陆失败！');
        }
      }

      return {
        phone,
        code,
        seconds,
        tips,
        showError,
        codeChange,
        getCode,
        end,
        start,
        loginForPhone
      };
    }
  });
</script>

<style lang="scss">
  .login {
    padding-top: 160rpx;
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
  }
  .title {
    height: 100rpx;
    font-size: 84rpx;
    text-align: center;
    font-family: Source Han Sans CN;
    font-style: normal;
    font-weight: bold;
    color: #d02129;
    margin-bottom: 80rpx;
  }
  .input-box {
    width: 600rpx;
    height: 50rpx;
    margin-bottom: 40rpx;
    padding: 26rpx;
    font-size: 32rpx;
  }
  input {
    border: 1px solid #e0e0e0;
  }
  input::-webkit-input-placeholder {
    color: #999999;
  }
  input::-moz-placeholder {
    color: #999999;
  }
  input::-ms-input-placeholder {
    color: #999999;
  }
  .alert-box {
    width: 640rpx;
    height: 60rpx;
    margin-bottom: 60rpx;
    padding: 0rpx 20rpx;
    font-size: 32rpx;
    line-height: 48rpx;
    display: flex;
    align-content: center;
    overflow: hidden;
    color: #ee593c;
    align-items: center;
  }
  .alert-box image {
    width: 30rpx;
    height: 30rpx;
    margin-right: 20rpx;
  }
  .login-btn {
    width: 680rpx;
    height: 100rpx;
    line-height: 100rpx;
    font-size: 36rpx;
    text-align: center;
    color: #ffffff;
    background: #618dff;
    outline: none;
    border: 0;
  }
  .login-tips {
    color: #999999;
    font-size: 30rpx;
    text-align: center;
    margin-top: 30rpx;
  }

  .login-wrap {
    display: flex;
    align-items: center;
    margin-bottom: 60rpx;

    .verification-code {
      width: 400rpx;
      margin-bottom: 0;
      margin-right: 20rpx;
    }

    .get-verification-code {
      width: 200rpx;
    }
  }
</style>
